//
//  Date+extension.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/10.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

/// DateFormatter, Calendar创建和释放比较消耗性能，所以可以直接创建一个常量
let dateformat = DateFormatter()
let calendar = Calendar.current

extension Date {
    /// 直接调用该接口，获取需求字符串
    static func sinTimeToRequriedTimStr(sinaTime: String) -> String {
        let date = Date.sinaTimeToDate(sinaTime: sinaTime)
        return date.dateToRequiredTimeString()
    }
    
    /// 将新浪的时间字符串转成Date对象
    static func sinaTimeToDate(sinaTime: String) -> Date {
        dateformat.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        dateformat.locale = Locale(identifier: "en")
        let date = dateformat.date(from: sinaTime)!
        return date
    }
    
    /// 将date转成需求的时间字符串
    func dateToRequiredTimeString() -> String {
        let seconds = Int(Date().timeIntervalSince(self))
        //1分钟以内
        if seconds < 60 {
            return "刚刚"
        }
        
        //大于1分钟，小于1小时
        if seconds < 60 * 60 {
            return "\(seconds/60)分钟前"
        }
        
        //大于1小时，小于1天
        if calendar.isDateInToday(self) {
            return "\(seconds/3600)小时前"
        }
        
        //昨天
        if calendar.isDateInYesterday(self) {
            let formatStr = "昨天 HH:mm"
            dateformat.dateFormat = formatStr
            return dateformat.string(from: self)
        }
        //昨天以前
        else {
//            //1. 获取前天的date
//            let qiantian = Date(timeInterval: -(3600*24*2), since: self)
//            //2. 获取前前天的，年月日
//            let qyear = calendar.component(.year, from: qiantian)
//            let qm = calendar.component(.month, from: qiantian)
//            let qd = calendar.component(.day, from: qiantian)
//            //3. 获取当前时间的年月日
//            //4. 比较年月日是否相等
//            //5. 格式化
//            //let qiantianStr = String(format: "前天 %02d:%02d", [小时，分])
            
            let currentYear = calendar.component(.year, from: Date())
            let timeYear = calendar.component(.year, from: self)
            //往年
            if timeYear != currentYear {
                let formatStr = "yyyy-MM-dd HH:mm"
                dateformat.dateFormat = formatStr
                return dateformat.string(from: self)
            }
            //今年
            else {
                let formatStr = "今年 MM-dd HH:mm"
                dateformat.dateFormat = formatStr
                return dateformat.string(from: self)
            }
        }
    }
}

extension Date {
    func dateToTimeStr() -> String {
        let formatStr = "yyyy-MM-dd HH:mm:ss"
        dateformat.dateFormat = formatStr
        return dateformat.string(from: self)
    }
}
